import { AxiosResponse } from "axios";
import { ElNotification } from "element-plus";
import { setTagDivHeight } from "./common";
import { IMP3Data, IRequestMsg, useRequestGet } from "./useRequest";

export interface IChangeTagMsg {
	tag: string;
	tags: string[];
	type: "add" | "delete" | "exist" | "none";
}

export async function fetchEditTags(key: string, tags: string[]) {
	const { data } = (await useRequestGet("media/edit", {
		key,
		tags: JSON.stringify(tags),
	})) as AxiosResponse<IRequestMsg<Array<IMP3Data>>>;

	return data;
}

export function mergeChangeTagMsg(msg: Partial<IChangeTagMsg>): IChangeTagMsg {
	return {
		tag: "",
		tags: [],
		type: "none",
		...msg,
	};
}

export function changeTagsHandler(msg: IChangeTagMsg, key?: string) {
	switch (msg.type) {
		case "none":
			return;
		case "exist":
			return existTagHandler(msg.tag);
		default:
			return editTagHandler(msg, key!);
	}
}

export function genNotification(
	msg: IChangeTagMsg,
	success: boolean = true
): {
	message: string;
	type: "success" | "error";
} {
	const text = `${msg.type === "add" ? "添加" : "删除"}标签 "${msg.tag}" `;

	return {
		message: text + (success ? "成功" : "失败"),
		type: success ? "success" : "error",
	};
}

export function editTagHandler(msg: IChangeTagMsg, key: string) {
	fetchEditTags(key, msg.tags).then(({ code }) => {
		ElNotification(genNotification(msg, code === 200));
		setTagDivHeight();
	});
}

export function existTagHandler(tag: string) {
	return ElNotification({
		message: `标签 "${tag}" 已存在`,
		type: "warning",
	});
}
